package hermesV2.services.HubService;


import java.util.Date;
import java.util.Properties;



import hermesV2.Message;
import hermesV2.agent.AbstractProtocol;
import hermesV2.agent.CommunicationException;
import hermesV2.agent.Identificator;
import hermesV2.agent.InteractionContainer;
import hermesV2.agent.ServiceAgent;
import hermesV2.util.HermesLogger;

/**
 *
 * @author Diego Bonura e Ezio Bartocci
 *
 *
 */
public class HandleAgentRequest extends Thread {
   /**
    * The message received by the ServiceAgent.
    */
   private Message msg;

   /**
    * The array of the base URIs stored into the property file.
    */
   private String[] baseURIs;

   /**
    * The array of the config files stored into the property file.
    */
   private String[] configFiles;

   /**
    * The array of the query files stored into the property file.
    */
   private String[] queries;

   /**
    * The array of the query names stored into the property file.
    */
   private String[] names;

   /**
    * The ServiceAgent caller.
    */
   private ServiceAgent sa;

   private AbstractProtocol hubProtocol;
   private Properties hubProp;

   /**
    * This is the constructor of the InputRequest thread.
    *
    * @param sa
    *            The ServiceAgent that uses the InputRequest threads.
    * @param msg
    *            The message received.
    */
   public HandleAgentRequest(ServiceAgent sa, Message msg, AbstractProtocol hubProtocol, Properties prop) {
       this.sa = sa;
       this.msg = msg;
       this.hubProtocol = hubProtocol;
       this.hubProp=prop;
       this.start();
   }

   /**
    * @see java.lang.Runnable#run()
    */
   public void run() {
       //Incomincio ad elaborare la richiesta
       InteractionContainer request = (InteractionContainer) msg.getObject();
       if (request.validate(hubProtocol)) {
           if (request.getInteractionName(hubProtocol).equalsIgnoreCase("RequestSendEmail")) {

               String to = (String)request.getParameter("to");
               String from = (String)request.getParameter("from");
               String subject = (String)request.getParameter("subject");
               String msgText = (String)request.getParameter("body");

               // create some properties and get the default Session
               Properties props = new Properties();
               //props.put("mail.smtp.host", hubProp.getProperty("EMAILSERVICEAGENT.SMTP.SERVER"));
               //Session session = Session.getInstance(props, null);
               //session.setDebug(false);
               try {
                   // create a message
                   //javax.mail.Message msgEmail = new MimeMessage(session);
                   //msgEmail.setFrom(new InternetAddress(from));
                   //InternetAddress[] address = {new InternetAddress(to)};
                   //msgEmail.setRecipients(javax.mail.Message.RecipientType.TO, address);
                   //msgEmail.setSentDate(new Date());
                   //msgEmail.setSubject(subject);
                   //msgEmail.setText(msgText);
                   //Transport.send(msgEmail);
                   //request.makeResponseInteraction(new Object[]{"ok"});
                   //response(msg.getSenderAgentId(), request);
            	   throw new MessagingException ();
               } catch (MessagingException mex) {
                   System.out.println( "qui6");

                   responseError(msg.getSenderAgentId());
               }
           } else if (request.getInteractionName(hubProtocol).equalsIgnoreCase("RequestSendEmailWithAttachment")) {
               String to                  = (String)request.getParameter("to");
               String from                = (String)request.getParameter("from");
               String subject             = (String)request.getParameter("subject");
               String msgText             = (String)request.getParameter("body");
               String attachment          = (String)request.getParameter("attachment");
               String attachmentName      = (String)request.getParameter("attachmentName");
               String attachmentMimeType  = (String)request.getParameter("attachmentMimeType");

               // create some properties and get the default Session
               Properties props = new Properties();
               //props.put("mail.smtp.host", emailProp.getProperty("EMAILSERVICEAGENT.SMTP.SERVER"));
               //Session session = Session.getInstance(props, null);
               //session.setDebug(false);
               try {
                 /*  // create a message
                   javax.mail.Message msgEmail = new MimeMessage(session);
                   msgEmail.setFrom(new InternetAddress(from));
                   InternetAddress[] address = {new InternetAddress(to)};
                   msgEmail.setRecipients(javax.mail.Message.RecipientType.TO, address);
                   msgEmail.setSentDate(new Date());
                   msgEmail.setSubject(subject);

                   MimeBodyPart textPart = new MimeBodyPart();
                   textPart.setContent(msgText, "text/plain");
                   MimeBodyPart attachFilePart = new MimeBodyPart();
                   attachFilePart.setContent (attachment, attachmentMimeType );
                   attachFilePart.setFileName(attachmentName);
                   Multipart mp = new MimeMultipart();
                   mp.addBodyPart(textPart);
                   mp.addBodyPart(attachFilePart);
                   msgEmail.setContent(mp);
                   Transport.send(msgEmail);
                   request.makeResponseInteraction(new Object[]{"ok"});
                   response(msg.getSenderAgentId(), request);*/
            	   throw new MessagingException ();
               } catch (MessagingException mex) {
                   System.out.println( "qui5");

                   responseError(msg.getSenderAgentId());
               }
           }else {
               System.out.println( "qui4");

               responseError(msg.getSenderAgentId());
           }



       } else {
           System.out.println( "qui3");

           responseError(msg.getSenderAgentId());

       }
   }


   private void responseError(Identificator receiver) {
       InteractionContainer ic = new InteractionContainer(new HubServiceProtocol());
       ic.makeInteraction("ErrorSendEmail","ko");
       try {
           sa.sendMessageToUserAgent(new Message(sa.getIdentificator(), receiver, ic));
       } catch (CommunicationException e) {
           System.out.println( "qua");

           HermesLogger.log(HermesLogger.WARNING, "Communication Error", e);
       }
   }

   private void response(Identificator receiver, InteractionContainer ic) {
       try {
           sa.sendMessageToUserAgent(new Message(sa.getIdentificator(), receiver, ic));
       } catch (CommunicationException e) {
           System.out.println( "qui");
           HermesLogger.log(HermesLogger.WARNING, "Communication Error", e);
       }
   }



}
